package com.doit.demo.day06;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @DATE 2022/2/20/14:50
 * @Author MDK
 * @Version 2021.2.2
 *
 *  ValueState的底层实现问题
 *   1.KeyedState底层是一个Map结构
 *   2.如果想要容错就必须开启checkPointing机制,并且按照Flink的状态API进行编程(将中间结果都保存在Flink的特殊变量中)
 *
 *    ValueState : Map<Key, Value>
 *    MapState   : Map<Key, Map<k, v>>
 *    ListState  : Map<Key, List<v>>
 *
 *
 **/
public class MapStateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //开启checkPoint
        env.enableCheckpointing(5000);
        //设置重启策略
        //env.setRestartStrategy(RestartStrategies.fixedDelayRestart(5,5000));

        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888, "\n",5);

        SingleOutputStreamOperator<Tuple3<String, String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple3<String, String, Integer>>() {
            @Override
            public Tuple3<String, String, Integer> map(String line) throws Exception {
                String[] fields = line.split(",");
                String province = fields[0];
                String city = fields[1];
                Integer money = Integer.parseInt(fields[2]);
                return Tuple3.of(province, city, money);
            }
            
        });

        KeyedStream<Tuple3<String, String, Integer>, String> keyedStream = tpStream.keyBy(t -> t.f0);

        SingleOutputStreamOperator res = keyedStream.map(new CityMoneyFunction());

        res.print();
        env.execute();

    }

    private static class CityMoneyFunction extends RichMapFunction<Tuple3<String, String, Integer>,Tuple3<String, String, Integer>>{

        private MapState<String, Integer> mapState;

        @Override
        public void open(Configuration parameters) throws Exception {
            //定义MapStateDescriptor
            MapStateDescriptor<String, Integer> stateDescriptor = new MapStateDescriptor<>("city-money-state", String.class, Integer.class);
            //初始化或恢复状态
            mapState = getRuntimeContext().getMapState(stateDescriptor);
        }

        @Override
        public Tuple3<String, String, Integer> map(Tuple3<String, String, Integer> input) throws Exception {
            String city = input.f1;
            Integer money = input.f2;
            Integer history = mapState.get(city);
            if(history==null){
                history = 0;
            }
            money+=history;
            mapState.put(city, money);
            input.f2 = money;
            return input;
        }

    }
}
